package k.daniel.databindingdemo;

import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import k.daniel.databindingdemo.bean.UserBean;
import k.daniel.databindingdemo.databinding.ActivitySimpleRecyclerViewBinding;
import k.daniel.databindingdemo.databinding.LayoutListviewItemBinding;
import k.daniel.databindingdemo.model.UserModel;

public class SimpleRecyclerViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivitySimpleRecyclerViewBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_simple_recycler_view);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        MyAdapter adapter= new MyAdapter(new UserModel().getUsers());
        binding.recyclerView.setAdapter(adapter);
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHodler<LayoutListviewItemBinding>>{
        List<UserBean> userBeanList;

        public MyAdapter(List<UserBean> userBeanList) {
            this.userBeanList = userBeanList;
        }

        @Override
        public MyViewHodler<LayoutListviewItemBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutListviewItemBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.layout_listview_item, parent, false);
            MyViewHodler<LayoutListviewItemBinding> holder = new MyViewHodler<LayoutListviewItemBinding>(binding.getRoot());
            holder.setBinding(binding);
            return  holder;
        }

        @Override
        public void onBindViewHolder(MyViewHodler<LayoutListviewItemBinding> holder, int position) {
            LayoutListviewItemBinding binding =  holder.getBinding();
            binding.setUser(userBeanList.get(position));
            binding.executePendingBindings();
        }

        @Override
        public int getItemCount() {
            return userBeanList.size();
        }

        class MyViewHodler<T> extends RecyclerView.ViewHolder{
            private T binding;
            public MyViewHodler(View itemView) {
                super(itemView);
            }
            public void setBinding(T binding) {
                this.binding = binding;
            }
            public T getBinding() {
                return this.binding;
            }
        }
    }
}
